/**
 * @description 数据字典
 * @author 李艳
 */
import React, {Component} from "react";
import {findDataDictionary,getDataDictItems,
  deleteDictItem,
  deleteDicCategory,
  saveDataDictItem, saveDicCategory,
} from "./service";
import {Button, Col, Input, message, Modal, Row} from "antd";
import connect from "react-redux/es/connect/connect";
import EditLeftModal from "./component/EditLeftModal";
import EditRightModal from "./component/EditRightModal";
import SimpleTable from "../../../commons/components/SimpleTable";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import DetailCard from "../../../commons/components/DetailCard";
import {searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import {rowGutter} from "../../../configs/DefaultConfig";
import {hide, show} from "../../../configs/SharedReducer";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";
import CheckAuth from "../../../commons/components/CheckAuth";

const Search = Input.Search;
const confirm = Modal.confirm;

class DataDictionary extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "数据字典"}];
    this.state = {
      data: [],
      leftSelectedRow: [],
      leftSearchValue: "",
      rightSearchValue: "",
      rightData: [],
      loading: false,
      rightSelectRow: [],
      leftModalVisible: false,
      rightModalVisible: false,
      confirmLoading: false,
      isLeftAdd: true,
      isRightAdd: true
    }
  }

  onLeftModalRef = (ref) => {
    this.leftModalRef = ref;
  };
  onRightModalRef = (ref) => {
    this.rightModalRef = ref;
  };

  componentWillMount() {
    this.getData()
  };

  //请求左边table数据
  getData = (param,refresh) => {
    this.props.show();
    findDataDictionary(param).then((result) => {
      if(refresh) {
        this.setState({data:result, leftSelectedRow: [], leftSearchValue: ""})
      }else{
        this.setState({data:result, leftSelectedRow: []})
      }
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  onLeftSelectRow = (tableSelectRow) => {
    if (tableSelectRow[0]) {
      this.getDataDictItems({categoryCode:tableSelectRow[0].code})
      this.setState({leftSelectedRow: tableSelectRow})
    }else{
      this.setState({leftSelectedRow: [],rightData: []})
    }
  };
  //请求右边table数据
  getDataDictItems = (param) => {
    this.setState({loading: true});
    getDataDictItems(param).then((result) => {
      this.setState({
        rightData: result&&result.data?result.data:[], rightSelectRow: [], rightSearchValue: ""
      });
    }).catch(err => {
    }).finally(() => {
      this.setState({loading: false});
    });
  };
  onAddLeftClick = () => {
    this.setState({leftModalVisible: true, isLeftAdd: true})
  };
  onEditLeftClick = (record) => {
    this.setState({leftEditData: record});
    this.setState({leftModalVisible: true, isLeftAdd: false})
  };
  handleLeftSearch = (value) => {
    this.setState({leftSearchValue: value});
    this.getData({quickValue:value});

  };

  //新增或编辑点击确定按钮事件
  handleEditLeft = () => {
    //表单数据同步
    if (this.leftModalRef && this.leftModalRef.props.form) {
      this.leftModalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, leftModalVisible: true});
          if (this.state.isLeftAdd) {
            delete values.id
          }
          saveDicCategory(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请左边数据角色组数据刷新本地数据
              this.getData({},this.state.isLeftAdd);
            } else {
              message.error(result.message ? result.message : "保存失败");
            }
          }).catch(err => {
          }).finally(() => {
            this.setState({confirmLoading: false, leftModalVisible: false});
          });
        }
      })
    }
  };

  handleLeftModalCancel = () => {
    this.setState({leftModalVisible: false})
  };
  onDeleteLeftClick = (record) => {
    this.setState({leftEditData: record});
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        thiz.props.show();
        deleteDicCategory(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            thiz.getData({},false);
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
          thiz.props.hide();
        })
      },
      onCancel() {
      },
    });
  };

  onTableSelectRow = (tableSelectRow) => {
    this.setState({rightSelectRow: tableSelectRow});
  };
  judgeLeftSelected = () => {
    if (!this.state.leftSelectedRow[0]) {
      message.error('请选择数据字典类型！');
      return false;
    }
    return true;
  };

  onAddRightClick = () => {
    if (!this.judgeLeftSelected()) return;
    this.setState({rightModalVisible: true, isRightAdd: true})
  };
  onEditRightClick = (record) => {
    this.setState({rightModalVisible: true, isRightAdd: false, rightEditData: record})
  };
  handleRightSearch = (value) => {
    searchListByKeyWithTag(this.state.rightData, {keyword: value}, ["code","tenantCode","remark", "name","value","valueName"]).then(res => {
      this.setState({rightData: res, rightSearchValue: value})
    })
  };

  //新增或编辑点击确定按钮事件
  handleEditRight = () => {
    //表单数据同步
    if (this.rightModalRef && this.rightModalRef.props.form) {
      this.rightModalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, rightModalVisible: true});
          if (this.state.isRightAdd) {
            delete values.id
          }
          saveDataDictItem(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请左边数据角色组数据刷新本地数据
              const {rightSearchValue,leftSelectedRow}=this.state;
              this.getDataDictItems({categoryCode:leftSelectedRow[0]?leftSelectedRow[0].code:null})
            } else {
              message.error(result.message ? result.message : "保存失败");
            }
          }).catch(err => {
          }).finally(() => {
            this.setState({confirmLoading: false, rightModalVisible: false});
          });
        }
      })
    }
  };

  handleRightModalCancel = () => {
    this.setState({rightModalVisible: false})
  };
  onDeleteRightClick = (record) => {
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        thiz.props.show();
        deleteDictItem(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            const {rightSearchValue,leftSelectedRow}=thiz.state;
            thiz.getDataDictItems({categoryCode:leftSelectedRow[0]?leftSelectedRow[0].code:null})
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
          thiz.props.hide();
        })
      },
      onCancel() {
      },
    });
  };

  render() {
    const leftColumns = [
      {
        title: "操作",
        width: 60,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth  key={"leftEdit"} operateCode={'BASIC-SJZD-LEFTEDIT'} >
                <a className={'row-operator-item'} onClick={() => this.onEditLeftClick(record)}>编辑</a>
              </CheckAuth>

              {/*<a className={'row-operator-item'} onClick={() => this.onDeleteLeftClick(record)}>删除</a>*/}
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 120
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200
      },
      {
        title: '描述',
        dataIndex: 'remark',
        width: 200
      },
        {
            title: '冻结',
            align: "center",
            width: 80,
            render: (text, record, index) => (
                <div>
                    <input type="checkbox" checked={record.frozen} disabled={true}/>
                </div>
            ),
        }
    ];
    const rightColumns = [
      {
        title: "操作",
        width: 60,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth  key={"rightEdit"} operateCode={'BASIC-SJZD-RIGHTEDIT'} >
              <a className={'row-operator-item'} onClick={() => this.onEditRightClick(record)}>编辑</a>
              </CheckAuth>
              {/*<a className={'row-operator-item'} onClick={() => this.onDeleteRightClick(record)}>删除</a>*/}
            </div>
          )
        }
      },
      {
        title: '租户代码',
        dataIndex: 'tenantCode',
        width: 120
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 120
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 140
      },
        {
            title: '值',
            width: 140,
            dataIndex: 'value'
        },
      {
        title: '值描述',
        width: 140,
        dataIndex: 'valueName'
      },
      {
        title: '描述',
        dataIndex: 'remark',
        width: 200
      },
        {
            title: '排序',
            dataIndex: 'rank',
            render: (text) => {
                return <div style={{textAlign: "right"}}>{text}</div>
            },
        },
        {
            title: '冻结',
            align: "center",
            width: 80,
            render: (text, record, index) => (
                <div>
                    <input type="checkbox" checked={record.frozen} disabled={true}/>
                </div>
            ),
        }
    ];
    const leftTitle = () => {
      return [
        <CheckAuth  key={"leftAdd"} operateCode={'BASIC-SJZD-LEFTADD'} >
          <Button style={{marginRight: '5px'}} type={"primary"}
                  onClick={this.onAddLeftClick}>新增</Button>
        </CheckAuth>
      ]
    };

    //表头搜索框
    const leftSearch = () => {
      return [
        <Search
          key="search"
          placeholder="输入关键字查询"
          onSearch={value => this.handleLeftSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    const title = () => {
      return [
        <CheckAuth key={"rightAdd"} operateCode={'BASIC-SJZD-RIGHTADD'} >
        <Button className={"primaryButton"} type={"primary"}
                onClick={this.onAddRightClick}>新增</Button>
        </CheckAuth>
      ]
    };

    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入关键字查询"
          onSearch={value => this.handleRightSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };

    const {rightSearchValue,rightData,data,loading,rightSelectRow,leftModalVisible,confirmLoading
    ,leftEditData,isLeftAdd,rightModalVisible,isRightAdd,rightEditData,leftSelectedRow}=this.state;
    return (
      <HeadBreadcrumb
        className={"allocation-page"}
        style={{overflow: "hidden"}}
      >
        <Row gutter={rowGutter}>
          {/*左边控件*/}
          <Col span={9} style={{height: "100%"}}>
            <DetailCard title="数据字典类型" style={{height: "100%"}}>
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{leftTitle()}</div>
                <div className={'tbar-search-box'}>{leftSearch()}</div>
              </div>
              <SimpleTable
                inCard={true}
                data={data}
                columns={leftColumns}
                loading={loading}
                onSelectRow={this.onLeftSelectRow}
              />
            </DetailCard>
          </Col>
          {/*右边的表格控件*/}
          <Col span={15}>
            <DetailCard title={"数据字典"} className={"child-card"}>
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{title()}</div>
                <div className={'tbar-search-box'}>{search()}</div>
              </div>
              <SimpleTable
                data={rightSearchValue?rightData.filter(item => item.tag === true) : rightData}
                columns={rightColumns}
                loading={loading}
                onSelectRow={this.onTableSelectRow}
                rowsSelected={rightSelectRow}
              />
            </DetailCard>

            <EditLeftModal
              modalVisible={leftModalVisible}
              confirmLoading={confirmLoading}
              handleOk={this.handleEditLeft}
              handleCancel={this.handleLeftModalCancel}
              onRef={this.onLeftModalRef}
              defaultValue={leftEditData ? leftEditData : {}}
              isAdd={isLeftAdd}
            />
            {rightModalVisible && <EditRightModal
              modalVisible={rightModalVisible}
              confirmLoading={confirmLoading}
              handleOk={this.handleEditRight}
              handleCancel={this.handleRightModalCancel}
              onRef={this.onRightModalRef}
              defaultValue={!isRightAdd &&rightEditData ? rightEditData : {}}
              categoryCode={leftSelectedRow[0] ? leftSelectedRow[0].code : {}}
              isAdd={isRightAdd}
            />}
          </Col>
        </Row>
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(DataDictionary))
